package com.example.demo.service;

import com.example.demo.entity.Article;
import com.example.demo.mapper.ArticleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ArticleService {
//    @Autowired
//    private ArticleMapper articleMapper;
//
//    public Article findById(Integer id) {
//        return articleMapper.findById(id).get();
//
//    }
//    public List<Article> findAll() {
//        return articleMapper.findAll();
//    }
//
//    public Article addArticle( String title, String content) {
//        Article article = new Article();
//        article.setTitle(title);
//        article.setContent(content);
//        return articleMapper.save(article);
//    }
//    public Article updateArticle(Integer id, String title, String content) {
//        Article article = new Article();
//        article.setId(id);
//        article.setTitle(title);
//        article.setContent(content);
//        return articleMapper.save(article);
//    }
//    public void deleteArticleById(Integer id) {
//        if (articleMapper.existsById(id))
//            articleMapper.deleteById(id);
//    }
@Autowired
private ArticleMapper articleMapper;
    @Cacheable(cacheNames ="article")
    public Article findById(Integer id) {
    if (articleMapper.findById(id).isPresent())
     return articleMapper.findById(id).get();

    return null;

    }


    public List<Article> findAll() {

        return articleMapper.findAll();
    }

    public Article addArticle(String title, String content) {
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        return articleMapper.save(article);
    }

    @CachePut(value = "article",key ="#article.id")
    public Article updateArticle(Article article)  {
//        Article article = new Article();
//        article.setId(id);
//        article.setTitle(title);
//        article.setContent(content);
        return articleMapper.save(article);
    }

    @CacheEvict(value = "article", key = "#id")
    public Integer deleteArticleById(Integer id) {
        if (articleMapper.existsById(id)) {
            articleMapper.deleteById(id);
            return 0;
        }
        return 1;
    }
    public Page<Article> findAllByPage(int page, int size) {
        Pageable pageable= PageRequest.of(page,size);
        return articleMapper.findAll(pageable);
    }


}
